package com.lzw.ddns;

import com.aliyuncs.IAcsClient;
import com.lzw.constant.DomainNameTypeEnum;
import com.lzw.http.IGetIPV4;
import com.lzw.http.IGetIPV6;
import com.lzw.service.IDNSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * 动态域名解析
 */
@Slf4j
@Component
public class DDNS {

    private final IDNSService service;
    private final IAcsClient client;
    @Value("${domain.name}")
    private String domainName;
    @Value("${rr.key.word:www}")
    private String rRKeyWord;
    @Autowired
    private IGetIPV4 ipv4;
    @Autowired
    private IGetIPV6 ipv6;

    private List<String> domainNameType;

    public DDNS(IDNSService service, IAcsClient client) {
        this.service = service;
        this.client = client;
    }

    @Value("${domain.name.type:A}")
    public void setDomainNameType(String domainNameType) {
        this.domainNameType = Arrays.asList(domainNameType.split(","));
    }

    @PostConstruct
    public void init() {
        for (String type : domainNameType) {
            try {
                DomainNameTypeEnum anEnum = DomainNameTypeEnum.valueOf(type);
                switch (anEnum) {
                    case A:
                        service.updateDomainRecord(type, ipv4.execution());
                        break;
                    case AAAA:
                        service.updateDomainRecord(type,  ipv6.execution());
                        break;
                    default:
                        break;
                }
            } catch (IllegalArgumentException e) {
                log.info("未知类型[{}]", type);
            }

        }

    }

}